jQuery(function(){
    var data = Array();  
    var selectedCategories = 0;
    var MAX_SELECTED_CATEGORIES = 4;//TODO: remove hardcode
    
    /*
     * Category
     */
    jQuery("div.CateContent ul#category_container li a").each(function(){
    	var $this = jQuery(this);
		var index = $this.attr("rel");
		var selectedClass = "selected"+index;
		
    	jQuery(this).click(function(){
    		if($this.hasClass(selectedClass)){
    			$this.removeClass(selectedClass);
    			if(selectedCategories > 0){
    				selectedCategories--;
    			}
    		}else{
    			if(selectedCategories < MAX_SELECTED_CATEGORIES){
    				$this.addClass(selectedClass);
    				selectedCategories++;
    			}
    		}
    		return false;
    	});
    	
    	if($this.hasClass(selectedClass)){
    		selectedCategories++;
    	}
    });    
    
    //jQuery("#registerSuccessful").delay(5000).slideUp(1000);
    
    jQuery(".InviteFriendResult .m input").button();
    
    jQuery("label[for=checkAll]").click(function(){
    	var $chkAll = jQuery(this);
    	if($chkAll.hasClass("checkbox_active")){
    		jQuery(".iMain label.ui-button").addClass("checkbox_active");
    		var count = jQuery(".iMain label.ui-button").length;
    		jQuery("#contactSelected").html(count);
    	}else{
    		jQuery(".iMain label.ui-button").removeClass("checkbox_active");
    		jQuery("#contactSelected").html(0);
    	}
//    	checkAllFriends();
    });        
    
    jQuery("input#txtPW").focus(function(){
    	var $pw = jQuery(this);    	    	
    	$pw.hide();
    	jQuery("input#pwPW").show();
    	jQuery("input#pwPW").focus();
    });
    
    jQuery("input#pwPW").blur(function(){
    	var $pw = jQuery(this);
    	var val = $pw.val();
    	if(val == ""){
    		$pw.hide();
    		jQuery("input#txtPW").show();
    	}
    }).keydown(function(e){
    	if(e.keyCode == 13 || e.which == 13){
    		loginGMAIL();
    	}
    });
    
    jQuery("input#txtUN").focus(function(){
    	var $pw = jQuery(this);
    	var val = $pw.val();
    	if(val == "Tài khoản Gmail"){
    		//$pw.attr("type", "password");
    		$pw.val("");
    	}
    }).blur(function(){
    	var $pw = jQuery(this);
    	var val = $pw.val();
    	if(jQuery.trim(val) == ""){
    		//$pw.attr("type", "text");
    		$pw.val("Tài khoản Gmail");
    	}
    });
    
    jQuery("#searchFButton").bind('click', function(){
        searchFriendFromBackend(jQuery("#searchF").attr("value"));
    });
    
    function loadFriendSuggested(friends){	      
        var $searchResult = jQuery("div.showHide_searchResult").html("");
        var $resultCount = jQuery("<label>").html("<span>"+ friends.length +"</span> kết quả được tìm thấy."); 
        $resultCount.appendTo($searchResult);
        if(friends != null && friends.length > 0){                
            var $ul = jQuery("<ul>");                
            for(var i=0; i<friends.length; i++){
                var $li = jQuery("<li>");
                $li.html("<a href='javascript:void(0);' class='addFindFriendPanel'><span></span><b>"+friends[i].username+"</b><u rel='"+friends[i].id+"' class='icon addFindFriend'></u></a>");
                $li.appendTo($ul).fadeIn();
            }
            $ul.appendTo($searchResult);	                
        }
        jQuery("a.addFindFriendPanel").click(function(){
        	var $this = jQuery(this);
            if(!$this.children("u.addFindFriend").hasClass("addFindFriendSelect")){
                $this.children("u.addFindFriend").addClass("addFindFriendSelect");
            }else{
            	$this.children("u.addFindFriend").removeClass("addFindFriendSelect");	
            }
        });    
    }
    
    function searchFriendInExistsData(name){
        var rs = Array();
        var index=0;
        var patt=new RegExp(name, "i");
        for(var i=0; i<data.items.length; i++)
        {	                
            if(patt.test(data.items[i].name)){
                rs[index] = data.items[i];
                index++;
            }	                
        }
        return rs;
    }
    
    //TODO: search the most common user only, not bring on full database
    //TODO: dedicate how many users want to get, -1 is no limited
    function searchFriendFromBackend(name){
    	UserManagerExt.searchUser(name, function(result){
    		loadFriendSuggested(result);
    	});            
    }     
    
    function bindAutocomplete(){
        jQuery("input.autocomplete").autocomplete(data, {
            minChars: 0,
            width: 310,
            matchContains: "word",
            autoFill: false,
            formatItem: function(row, i, max) {
                return row.username;
            },
            formatMatch: function(row, i, max) {
                return row.username;
            },
            formatResult: function(row) {
                return row.username;
            }
        }).result(function(event, data){
        	if(!data){
        		UserManagerExt.getUsers(function(result){
		        	data = result;		            
		            bindAutocomplete();
		        }); 
        	}
        });
    } 
    
    //bindAutocomplete();
});

function passStep1(){
//	var friends = new Array(); 
//	jQuery("a.addFindFriendPanel").each(function(){
//		jQuery(this).children("u.addFindFriendSelect").each(function(i){
//			var $u = jQuery(this);
//			friends[i] = $u.attr("rel");		
//		});
//	});	
	
//	UserManagerExt.addFriends(friends, showEmailImporter);
	
	var addCategoryIds = new Array();
	var removeCategoryIds = new Array();
	var categories = "";
	var categories1 = "";
	jQuery("div.CateContent ul#category_container li a").each(function(){
		var $this = jQuery(this);
		var index = $this.attr("rel");
		var selectedClass = "selected"+index;
		if($this.hasClass(selectedClass)){
			categories += index + ",";
		}else{
			categories1 += index + ",";
		}
	});
	addCategoryIds = categories.split(",");
	removeCategoryIds = categories1.split(",");
	UserManagerExt.addCategories(addCategoryIds, function(result){
		showEmailImporter();
//		if(result != -1)
//			showEmailImporter();
//		else
//			iAlert("Không thể thêm danh mục cho bạn. Vui lòng thử lại sau.")
	});
	UserManagerExt.removeCategories(removeCategoryIds);	
}   

//for restore
function showEmailImporterV1(){
	jQuery("span.step2").parents("li").addClass("passStep");
	jQuery("span.step3").parents("li").removeClass("passStep");
	
	jQuery("#chooseCategory").hide();
	jQuery(".InviteFriendResult").hide();
	jQuery(".inputFormApi").hide(); 
	jQuery(".InviteFriendResult").hide();
	
	jQuery("#InviteFriend").show();
	jQuery(".FriendsearchAPIStep").show();
	jQuery(".logoGmail").click(function() {
		showGMAIL();
		//window.open("/googleContact", "login", "width: 500, height: 300");
	});
	jQuery("#txtUN").attr("readonly",false);
	jQuery("#pwPW").attr("readonly",false);
	jQuery("#pwPW").attr("readonly",false);
	jQuery("a#findFriendInMail").click(loginGMAIL);
}

//temp show gmail
function showEmailImporter(){
	jQuery("span.step2").parents("li").addClass("passStep");
	jQuery("span.step3").parents("li").removeClass("passStep");
	
	jQuery("#chooseCategory").hide();
	jQuery(".InviteFriendResult").hide();
	jQuery(".inputFormApi").hide(); 
	jQuery(".InviteFriendResult").hide();
	
	jQuery("#InviteFriend").show();
	jQuery(".FriendsearchAPIStep").show();
	jQuery(".logoGmail").click(function() {
		showGMAIL();
	});
	jQuery("#txtUN").attr("readonly",false);
	jQuery("#pwPW").attr("readonly",false);
	jQuery("#pwPW").attr("readonly",false);
	jQuery("a#findFriendInMail").click(loginGMAIL);
	
	showGMAIL();
}

function showGMAIL(){
	jQuery(".FriendsearchAPIStep").hide();
	jQuery(".inputFormApi").show();
	jQuery("#txtUN").attr("readonly",false).css('border-color', 'black');;
	jQuery("#txtPW").attr("readonly",false).css('border-color', 'black');;
	jQuery("#pwPW").attr("readonly",false);
	jQuery(".InviteFriendResult").hide();
	jQuery("label[for=checkAll]").removeClass("checkbox_active").attr("aria-pressed", false);
	jQuery("#contactSelected").html(0);
}

function loginGMAIL(){
	var $this = jQuery(this);
	$this.parent("div.iGoal_button").addClass("button3_1");
	var $u = jQuery("#txtUN").attr("readonly",true);
	var $p = jQuery("#pwPW").attr("readonly",true);
	var u = $u.val();
	var p = $p.val();
	// gmail sample
	if(u.indexOf('@gmail.com') == -1){
		u+='@gmail.com';
	}
	var v = "GMAIL";
	jQuery(".inputFormApi").hide();
	jQuery("div#loader").show();
	UserManagerExt.findContacts(v, u, p, function(contacts){    	
		if(contacts.length == 0){
			$u.attr("readonly",false).css('border-color', 'red');
			$p.attr("readonly",false).css('border-color', 'red');
			$this.parent("div.iGoal_button").removeClass("button3_1");
			jQuery(".inputFormApi").show();
			jQuery("div#loader").hide();
			return false;
		}
					
		$this.parent("div.iGoal_button").removeClass("button3_1");			
		passStep2(contacts);
	});
	return false;
}

function checkAllFriends(){
	var $chkAll = jQuery("label[for=checkAll]");	
	jQuery("input.ui-helper-hidden-accessible[type=checkbox]").attr("checked",true);
	jQuery(".iMain label.ui-button").addClass("checkbox_active");
	var count = jQuery(".iMain label.ui-button").length;
	jQuery("#contactSelected").html(count);
}

function passStep2(contacts){    	
	jQuery(".FriendsearchAPIStep").hide();
	jQuery(".inputFormApi").hide();
	jQuery("div#loader").hide();
	
	buildContactList(contacts);    	    
	jQuery(".InviteFriendResult .m input").button();
	jQuery("input#checkAll").attr("checked",true);
	jQuery("label[for=checkAll]").addClass("checkbox_active").attr("aria-pressed", true);
	checkAllFriends();
	jQuery("label.ui-button:not(label[for=checkAll])").click(function(){
		var $this = jQuery(this);		
		var count = jQuery(".iMain label.checkbox_active:not(label[for=checkAll])").length;
		count = parseInt(count);		
		jQuery("#contactSelected").html(count);
	});
	jQuery(".InviteFriendResult").show();
	jQuery("#backtoStep2").click(function(){
		passStep1();
	});    	    	
}

function buildContactList(contacts){
	var $ul = jQuery(".iMain #contactList");
	$ul.html("");//clear old data
	for(var i=0; i<contacts.length; i++){
		var contact = contacts[i];
		var $li = jQuery("<li/>");
		var clz = "user"+i;
		var html = "<div class='col1'><input type='checkbox' id='"+clz+"' /><label for='"+clz+"'><b>"+contact.displayEmail+"</b></label></div>";
		html += "<div class='col2'>"+contact.displayName+"</div>";
		if(!contact.id){
			html += "<div class='col3'>chưa là thành viên IGoal</div>";
		}else{
			html += "<div class='col3 memberReady'>thành viên IGoal</div>";
		}    		
		$li.append(html);
		$li.appendTo($ul);
	}
}

function registerComplete(){	
	jQuery("span.step3").parents("li").addClass("passStep");
	jQuery(".InviteFriendResult").hide();
	jQuery(".InviteFriend").hide();
	jQuery("#inviteFriendFinish").show();
	jQuery("a.finish").show();
	setTimeout(gotoDashboard, 3000);
}

function gotoDashboard(){
	window.location = ctx+'/dashboard.html';
}